package com.wn.carport.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;

import com.wn.carport.auth.JWTUtil;
import com.wn.carport.feign.UserFeign;
import com.wn.carport.mapper.AreaVillageMappper;
import com.wn.carport.mapper.CarPortMapper;
import com.wn.carport.mapper.UserMapper;
import com.wn.carport.param.CarportParm;
import com.wn.carport.param.CarportSearchParam;
import com.wn.carport.resp.PgRe;
import com.wn.carport.service.CarPortService;
import com.wn.carport.util.PageInfoUtil;
import com.wn.carport.vo.CarPortAreaVillageVo;

import com.wn.common.entity.Const;
import com.wn.common.entity.MyPage;
import com.wn.common.entity.MyParam;
import com.wn.common.entity.MyRsp;
import com.wn.common.pojo.AreaVillage;
import com.wn.common.pojo.CarPort;
import com.wn.common.pojo.User;
import com.wn.common.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;


/**
 * @BelongsProject: shared_parking
 * @BelongsPackage: com.wn.carport.service.impl
 * @Author: 刘辉
 * @CreateTime: 2020-06-11 14:23
 * @Description:
 */

/**
 * @Transactional：开启对事务的支持
 */
@Service
@Transactional
public class CarPortImpl implements CarPortService {

    private final static Logger logger = LoggerFactory.getLogger(CarPortImpl.class);
    @Autowired
    private CarPortMapper carPortMapper;

    @Autowired
    private AreaVillageMappper areaVillageMappper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserFeign userFeign;
    /**
     * 根据车位主键查询车位信息
     * @param cpId
     * @return
     */
    @Override
    public CarPort getCarPortById(String cpId) {

        CarPort carPort = carPortMapper.getCarPortById(cpId);

        return carPort;
    }


    /**
     * 查询车位列表
     * @return
     */
    @Override
    public PageInfo<CarPort> getCarPortlAll(MyParam<CarPort> myParam) {

        /*开启分页*/
        PageHelper.startPage(myParam.getMyPage().getPageNum(),myParam.getMyPage().getPageSize());

        /*获取排序规则数组*/
        String[] pageParam = myParam.getPageParam();

        /*遍历排序规则数组*/
        for (int i=0;i<pageParam.length;i++){
            PageHelper.orderBy(pageParam[i]);
        }

        List<CarPort> carPolAll = carPortMapper.getCarPolAll();
        System.out.println("列表："+carPolAll);

        return new PageInfo<CarPort>(carPolAll);
    }

    /**
     *根据车位主键删除车位信息
     * @param cpId
     * @return
     */
    @Override
    public Integer deleteCarPort(String cpId) {

        Integer integer = carPortMapper.deleteCarPort(cpId);

        return integer;
    }

    @Override
    public MyRsp updateCarPort(CarportParm carportParm) {
        CarPort carPort = carportParm.getCarPort();
        //将图片上传到云上
        if (carportParm.getMainImgBase64() != null){
            String imageUrl = FileUtil.uploadImage(carportParm.getMainImgBase64());
            carPort.setCpMainImage(imageUrl);
        }
        Integer updateCarPort = carPortMapper.updateCarPort(carPort);

        return updateCarPort > 0 ? MyRsp.success("修改成功"):MyRsp.error().msg("修改失败");
    }


    /**
     * 添加车位信息
     * @param carPortAreaVillageVo
     * @return
     */
    @Override
    public Integer addCartPort(CarPortAreaVillageVo carPortAreaVillageVo) {

        Integer addCartPort = carPortMapper.addCartPort(carPortAreaVillageVo);

        return addCartPort;
    }

    /**
     * 根据主键物理删除车位信息
     * @param cpId
     * @return
     */
    @Override
    public Integer deleteCarPortPhy(String cpId) {

        Integer deleteCarPortPhy = carPortMapper.deleteCarPortPhy(cpId);

        return deleteCarPortPhy;
    }

    /**
     * 高级检索车位信息
     * @param superSearchKeyWord
     * @return
     */
    @Override
    public List<CarPort> superSearch(String superSearchKeyWord) {

        List<CarPort> carPorts = carPortMapper.superSearch(superSearchKeyWord);

        return carPorts;
    }

    /**
     * 查询出所有的地区名称（方便后续根据地区来进行查询小区）
     * @return
     */
    @Override
    public List<AreaVillage> getAreaAll() {

        List<AreaVillage> areaAll = carPortMapper.getAreaAll();

        return areaAll;
    }
    /*查询所有的地区/返回集合*/
    @Override
    public List<AreaVillage> getAreaAll01() {

        List<AreaVillage> areaAll01 = carPortMapper.getAreaAll01();

        return areaAll01;
    }

    /**
     * 根据地区名称查询其下所有的小区
     * @param aName
     * @return
     */
    @Override
    public List<AreaVillage> getVillageByAreaName(@RequestBody String aName) {

        List<AreaVillage> villageByAreaName = carPortMapper.getVillageByAreaName(aName);

        return villageByAreaName;
    }

    @Override
    public List<AreaVillage> getVillageByAreaId(String aid) {

        List<AreaVillage> villageByAreaId = carPortMapper.getVillageByAreaId(aid);

        return villageByAreaId;
    }

    /**
     * 根据小区查询旗下的车位
     * @param aName
     * @return
     */
    @Override
    public List<CarPort> getCarPortByVillage(String aName) {

        List<CarPort> carPortByVillage = carPortMapper.getCarPortByVillage(aName);

        return carPortByVillage;
    }

    /**
     * 查询车位数据的总数据条数
     * @return
     */
    @Override
    public Integer getTotal() {
        Integer total = carPortMapper.getTotal();
        return total;
    }



    /*分页查询车位首页展示*/
    @Override
    public PgRe getCarPortAll03(Integer page, Integer rows,String aName) {

        if (aName!=null && !aName.equals("")){
            aName = "%"+aName+"%";
        }

        /*开启分页*/
        PageHelper.startPage(page, rows);

        /*查询出的所有数据*/
        List<CarPortAreaVillageVo> carPortAll03 = carPortMapper.getCarPortAll03(aName);

        PageInfo<CarPortAreaVillageVo> pageInfo = new PageInfo<>(carPortAll03);

        /**
         * 第一个参数：
         *  pageInfo.getTotal()：数据总条数
         *
         * 第二个参数：
         *  查询出的数据集合
         */
        long pageInfoTotal = pageInfo.getTotal();
        return new PgRe((int) pageInfoTotal,carPortAll03);
    }

    @Override
    public List<CarPortAreaVillageVo> getCarPortByAreaVillageName(String aName) {

        List<CarPortAreaVillageVo> carPortByAreaVillageName = carPortMapper.getCarPortByAreaVillageName(aName);

        return carPortByAreaVillageName;
    }

    /**
     * 车位的上下架
     * @param cpId
     * @param cpStatus
     * @return
     */
    @Override
    public Integer upDownShelf(String cpId, Integer cpStatus) {

        Integer upDownShelf = carPortMapper.upDownShelf(cpId, cpStatus);

        return upDownShelf;
    }

    @Override
    public AreaVillage getAreaNameByCpId(String cpId) {

        System.out.println("**"+cpId);

        AreaVillage areaNameByCpId = carPortMapper.getAreaNameByCpId(cpId);

        System.out.println("++"+areaNameByCpId);
        return areaNameByCpId;
    }

    /**
     * 查询车位的价格/地址（区域表/车位表联合）
     * @param cpId
     * @return
     */
    @Override
    public CarPortAreaVillageVo getCarPortAreaVo(String cpId) {

        CarPortAreaVillageVo carPortAreaVo = carPortMapper.getCarPortAreaVo(cpId);

        return carPortAreaVo;
    }

    /**
     * 根据地区名称查看下面的小区 集合
     * @param aName
     * @return
     */
    @Override
    public List<AreaVillage> getAreaVillagedo(String aName) {

        List<AreaVillage> areaVillagedo = carPortMapper.getAreaVillagedo(aName);

        return areaVillagedo;
    }

    @Override
    public AreaVillage getvillageIdByVname(String aName) {
        AreaVillage areaVillage = carPortMapper.getvillageIdByVname(aName);

        return areaVillage;
    }

    /**
     *
     * @param cpId
     * @return
     */
    @Override
    public CarPortAreaVillageVo getCarportVo(String cpId) {
        CarPortAreaVillageVo carportVo = carPortMapper.getCarportVo(cpId);

        return carportVo;
    }

    /**
     *
     * @param
     * @return
     */
    @Override
    public AreaVillage getAreaName(String vName) {

        AreaVillage areaName = carPortMapper.getAreaName(vName);

        return areaName;
    }

    /**
     * 根据小区名称或者关键字获取这个小区下面所有车位对象
     * @param
     * @return
     */
    @Override
    public MyRsp getListByVnameOrKeyword(CarportSearchParam carportSearchParam) {

        List<CarPort> carPortList = null;
        if(StringUtil.isEmpty(carportSearchParam.getSupersearchkey())){
            carPortList = carPortMapper.getAllCarPort(carportSearchParam.getCarPort());
        }else{//有关键字
            carPortList = carPortMapper.superSearch3(carportSearchParam.getSupersearchkey());
        }
        return MyRsp.success(carPortList);
    }

    /**
     * 列表展示车位信息
     * @return
     */
    @Override
    public Object carPortList(Integer page,Integer rows,Integer cpCode,String superSearchKeyWord) {
        MyParam<CarPort> param = new MyParam<>();
        param.setMyPage(new MyPage(page, rows));
        param.setSuperSearchKeyWord(superSearchKeyWord);

        CarPort carPort = new CarPort();
        if(cpCode != null && cpCode >= 0){
            carPort.setCpCode(cpCode);
        }
        carPort.setIsDeleted(0);
        param.setT(carPort);
        //logger.info("测试：{}",param);
        PageHelper.startPage(param.getMyPage().getPageNum(),param.getMyPage().getPageSize());
        List<CarPort> carPortList = carPortMapper.getAllCarPort(param.getT());

        if(!StringUtil.isEmpty(param.getSuperSearchKeyWord())){
            //有关键词
            List<CarPort> carPorts = carPortMapper.superSearch(param.getSuperSearchKeyWord());
            carPortList.retainAll(carPorts);
        }
        Map<String, Object> map = PageInfoUtil.List2Map(carPortList);
        return map;
    }

    /**
     * 支持分页和高级检索
     * @param param
     * @return
     */
    @Override
    public Object getAllCarPort(MyParam<CarPort> param) {

        //没有高级检索关键词，根据里面的数据普通分页排序查询
        PageHelper.startPage(param.getMyPage().getPageNum(),param.getMyPage().getPageSize());
        for(int i = 0; param.getPageParam() != null && i < param.getPageParam().length;i++){
            PageHelper.orderBy(param.getPageParam()[i]);
        }

        List<CarPort> carPortList = carPortMapper.getAllCarPort(param.getT());
        PageInfo<CarPort> carPortPageInfo = new PageInfo<>(carPortList);

        return carPortPageInfo;
    }

    /**
     * 展示物业查看的车位信息
     * @param page
     * @param rows
     * @param token
     * @return
     */
    @Override
    public Object carPortListByProperty(Integer page, Integer rows,Integer cpCode,String superSearchKeyWord, String token) {
        //解析token,获取物业id
        User currentUser = JWTUtil.parseToken(token);
        MyParam<CarPort> param = new MyParam<>();
        param.setMyPage(new MyPage(page, rows));
        param.setSuperSearchKeyWord(superSearchKeyWord);
        CarPort carPort = new CarPort();
        if(cpCode != null && cpCode >= 0){
            carPort.setCpCode(cpCode);
        }
        carPort.setPropertyid(currentUser.getUId());
        carPort.setIsDeleted(0);
        param.setT(carPort);
        //logger.info("param,{}",param);
        PageHelper.startPage(param.getMyPage().getPageNum(),param.getMyPage().getPageSize());
        List<CarPort> carPortList = carPortMapper.getAllCarPort(param.getT());
        if(!StringUtil.isEmpty(param.getSuperSearchKeyWord())){
            //有关键词
            List<CarPort> carPorts = carPortMapper.superSearch2(param.getSuperSearchKeyWord());
            carPortList.retainAll(carPorts);
        }
        Map<String, Object> map = PageInfoUtil.List2Map(carPortList);
        return map;
    }

    @Override
    public Object carPortListByLessor(Integer page, Integer rows, Integer cpCode, String superSearchKeyWord, String token) {
        //解析token,获取出租方id
        User currentUser = JWTUtil.parseToken(token);
        MyParam<CarPort> param = new MyParam<>();
        param.setMyPage(new MyPage(page, rows));
        param.setSuperSearchKeyWord(superSearchKeyWord);
        CarPort carPort = new CarPort();
        if(cpCode != null && cpCode >= 0){
            carPort.setCpCode(cpCode);
        }
        carPort.setLessorid(currentUser.getUId());
        carPort.setIsDeleted(0);
        param.setT(carPort);
        //logger.info("param,{}",param);
        PageHelper.startPage(param.getMyPage().getPageNum(),param.getMyPage().getPageSize());
        List<CarPort> carPortList = carPortMapper.getAllCarPort(param.getT());
        if(!StringUtil.isEmpty(param.getSuperSearchKeyWord())){
            //有关键词
            List<CarPort> carPorts = carPortMapper.superSearch2(param.getSuperSearchKeyWord());
            carPortList.retainAll(carPorts);
        }
        Map<String, Object> map = PageInfoUtil.List2Map(carPortList);
        return map;
    }

    /**
     * 物业方动态添加车位
     * @param carportParm
     * @return
     */
    @Override
    public MyRsp addCarport(CarportParm carportParm,String token) {
        CarPort carPort = carportParm.getCarPort();

        carPort.setCpId(UUID.randomUUID().toString());
         //需要获取物业名称和物业id
        MyRsp myRsp = userFeign.getUserInfoBytoken(token);

        LinkedHashMap<String,Object> currentUser = (LinkedHashMap<String, Object>) myRsp.getContent();
        carPort.setPropertyid((String) currentUser.get("uid"));
        carPort.setPrpertyname((String) currentUser.get("realname"));
        carPort.setPropertphone((String) currentUser.get("tel"));
        //小区名
        String vName = (String) currentUser.get("address");
        //通过小区名获取地区名
        AreaVillage areaVillage = carPortMapper.getAreaName(vName);
        carPort.setVName(vName);
        carPort.setAName(areaVillage.getAName());
        //判断这个物业中车位名称是否重复
        Integer integer1 = carPortMapper.exsitCarname(carPort);
        if(integer1 > 0 ){
            return myRsp.error().msg("车位名称重复了").code(Const.Status.STATUS_HAS_name);
        }
        //上传主图
        String mainImgBase64 = carportParm.getMainImgBase64();
        carPort.setCpMainImage(FileUtil.uploadImage(mainImgBase64));
        Integer integer = carPortMapper.addCarport(carPort);

        return integer > 0 ? MyRsp.success("添加车位成功"):MyRsp.error().msg("添加车位失败");
    }

    /**
     * 出租客添加车位
     * @param carportParm
     * @param token
     * @return
     */
    @Override
    public MyRsp addCarportByLessor(CarportParm carportParm, String token) {
        CarPort carPort = carportParm.getCarPort();

        carPort.setCpId(UUID.randomUUID().toString());
        //需要获取物业名称和物业id
        MyRsp myRsp = userFeign.getUserInfoBytoken(token);
        LinkedHashMap<String,Object> currentUser = (LinkedHashMap<String, Object>) myRsp.getContent();
       //出租客id
        carPort.setLessorid((String) currentUser.get("uid"));
        //出租客名称
        carPort.setLessorname((String) currentUser.get("realname"));
        //出租客电话
        carPort.setLessorphone((String) currentUser.get("tel"));
        //小区名
        String vName = (String) currentUser.get("address");
        //通过小区名获取地区名
        AreaVillage areaVillage = carPortMapper.getAreaName(vName);
        carPort.setVName(vName);
        carPort.setAName(areaVillage.getAName());
        //通过小区名获取create_user_id即物业id
        String propertyId = areaVillageMappper.getCreateUserIdByName(carPort.getVName());
        //通过物业id，获取物业对象
        User propertUser = userMapper.getUserById(propertyId);
        carPort.setPropertyid(propertyId);
        carPort.setPropertphone(propertUser.getTel());
        carPort.setPrpertyname(propertUser.getRealname());
        //判断这个物业中车位名称是否重复
        Integer integer1 = carPortMapper.exsitCarname(carPort);
        if(integer1 > 0 ){
            return myRsp.error().msg("车位名称重复了").code(Const.Status.STATUS_HAS_name);
        }
        //上传主图
        String mainImgBase64 = carportParm.getMainImgBase64();
        carPort.setCpMainImage(FileUtil.uploadImage(mainImgBase64));
        Integer integer = carPortMapper.addCarport(carPort);
        return integer > 0 ? MyRsp.success("添加车位成功"):MyRsp.error().msg("添加车位失败");
    }

    /**
     * 批量删除车位
     * @param ids
     * @return
     */
    @Override
    public MyRsp deleteSomeCarport(String[] ids) {
        Integer integer = carPortMapper.deleteSomeCarport(ids);
        return integer > 0 ?  MyRsp.success("删除成功"):MyRsp.error().msg("删除失败");
    }


}
